/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistencia;


import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.Properties;
import javax.swing.JOptionPane;

/**
 *
 * @author Eugenio
 */
public class Conexion {

    private Connection con;
    private ResultSet rs;
    private PreparedStatement ps;
    private String username;
    private String password;
    private String url;
    private static Conexion instancia;


    public Conexion() {
        Properties propiedades = new Properties();
        FileInputStream lector;
        try {
            lector = new FileInputStream("database.properties");
            propiedades.load (lector);
            lector.close();
            username = propiedades.getProperty("jdbc.username");
            password = propiedades.getProperty("jdbc.password");
            url = propiedades.getProperty("jdbc.url");
            con = DriverManager.getConnection(url, username, password);
           
        } catch (IOException ex) {
           JOptionPane.showMessageDialog(null, "Error en el flujo de entrada o salida");
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            ex.getErrorCode();
            JOptionPane.showMessageDialog(null, "Error de tipo Sql");
                    
        }
        
    
    }

    public static Conexion getInstancia (){
        if(instancia == null){
            instancia = new Conexion();
        }
        return instancia;
    }

    public void cerrarConexion(){
        try {
            con.close();
            rs.close();
            ps.close();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error de tipo Sql");
        ex.printStackTrace();
        }
      
    }


    public PreparedStatement hacerEnunciado (String enunciado){
        try {
            ps = con.prepareStatement(enunciado);
        } catch (SQLException ex) {
             JOptionPane.showMessageDialog(null, "Error realizando enunciado");
        }
        return ps;
    }

    public ResultSet hacerConsulta (String consulta){
        try {
            rs = ps.executeQuery(consulta);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error realizando consulta");
        }
        return rs;
    }

    public Connection getConexion (){
        return con;
    }


}
